<template>
  <div class="page-trend page-wrapper">
    <c-box title="综合排名">
      <load-data-wrapper :status="load1">
        <echart-wrapper :option="option1"></echart-wrapper>
      </load-data-wrapper>
      <!-- <div id="echarts-1" class="echarts"></div> -->
    </c-box>
    <c-box title="本周环比上周" class="echarts2-wrapper">
      <div class="date-select">
        <span>选择日期</span>
        <el-date-picker
          v-model="selectedWeek"
          value-format="yyyy-MM-dd"
          type="week"
          format="yyyy-M-d"
          placeholder="选择周"
          size="mini"
          @change="dateChange"
        ></el-date-picker>
      </div>
      <load-data-wrapper :status="load2">
        <echart-wrapper :option="option2"></echart-wrapper>
      </load-data-wrapper>
    </c-box>
    <c-box :title="curYear + '-' + curMonth + '月购买电量消费'">
      <load-data-wrapper :status="load4">
        <echart-wrapper :option="option4"></echart-wrapper>
      </load-data-wrapper>
    </c-box>
    <c-box title="年用电量" class="echarts3-wrapper">
      <load-data-wrapper :status="load3">
        <div class="power-wrapper">
          <div class="year-power">
            <div>
              <div>
                <p>电量</p>
                <p>(kw.h/年)</p>
              </div>
            </div>
            <div class="echarts">
              <echart-wrapper :option="option3" :click-handle="echart3Click"></echart-wrapper>
            </div>
          </div>
          <div class="month-power">
            <echart-wrapper :option="option5" :click-handle="echart5Click"></echart-wrapper>
          </div>
        </div>
      </load-data-wrapper>
    </c-box>
    <c-box title="月用电量">
      <load-data-wrapper :status="load3">
        <echart-wrapper :option="option6"></echart-wrapper>
      </load-data-wrapper>
      <!-- <div id="echarts-6" class="echarts"></div> -->
    </c-box>
  </div>
</template>

<script>
import {
  colors,
  textColor,
  title,
  legend,
  color,
  activeColor,
  color1,
  activeColor1,
  grid,
  tooltip
} from "@/utils/echarts";
import {
  getMonthBuyElec,
  getWeeksPower,
  getDayBuyElec,
  getScoreRank
} from "@/api/power.js";
import {
  getMonthDay,
  parseTime,
  toWanKwH,
  getLastMonth,
  getLastDayOfMonth
} from "@/utils";
import { uniq, forEach } from "lodash";
import CBox from "@/components/PageCard";
import LoadDataWrapper from "../../components/base/LoadDataWrapper";
import EchartWrapper from "../../components/EchartWrapper";
const now = new Date();
const curDate = getLastDayOfMonth(getLastMonth(now));
export default {
  name: "Trend",
  components: { CBox, LoadDataWrapper, EchartWrapper },
  data() {
    return {
      yearValue: [],
      curYear: curDate.getFullYear(),
      curMonth: curDate.getMonth() + 1,
      selectMonthes: [],
      dateValue: {},
      selectedWeek: parseTime(curDate, "{y}-{m}-{d}"),
      weeksPower: null,
      load1: "loading",
      load2: "loading",
      load3: "loading",
      load4: "loading",
      load6: "loading",
      option1: null,
      option2: null,
      option3: null,
      option4: null,
      option5: null,
      option6: null
    };
  },
  computed: {
    comId() {
      return this.$store.getters.comId;
    },
    curMonthPower() {
      try {
        const yp = this.yearValue.find(
          e => parseInt(e.year) === curDate.getFullYear()
        );
        const mp =
          yp.cliesMonth &&
          yp.cliesMonth.find(e => parseInt(e.month) === this.curMonth);
        return mp || null;
      } catch (e) {
        return null;
      }
    }
  },
  async mounted() {
    this.setOption1();
    this.setOption2();
    try {
      const res = await getMonthBuyElec(this.comId);
      if (res.data instanceof Array && res.data.length === 0) {
        this.load3 = this.load4 = this.load6 = "empty";
        return;
      }
      this.yearValue = res.data;
      this.getYearMonth();

      this.setOption4();

      this.load3 = this.load6 = "load";
      this.setOption3();
      this.setOption5();
      this.getDatePower(this.selectMonthes[0]);
    } catch (e) {
      console.error(e);
      this.load3 = this.load4 = "error";
      this.$message.error("加载数据失败!!");
    }
  },
  methods: {
    async setOption1() {
      try {
        let _data = await getScoreRank();
        if (!_data || _data.length === 0) {
          this.load1 = "empty";
          return;
        }
        _data = _data.reverse();
        const data = _data.map((d, i) => {
          d.itemStyle = {
            color: colors[i]
          };
          d.value = parseFloat(d.value).toFixed(1);
          return d;
        });
        const xData = _data.map(d => d.name);
        const opt = {
          legend: { top: "1%", show: false },
          // title: {
          //   text: "综合排名",
          //   ...title
          // },
          tooltip: {},
          xAxis: [{ name: "万kw.h", show: false, max: 100 }],
          yAxis: [
            {
              type: "category",
              axisLine: { show: false, lineStyle: { color: textColor } },
              axisTick: { show: false },
              data: xData
            }
          ],
          grid: {
            ...grid,
            right: "10%"
          },
          series: [
            {
              type: "bar",
              name: "排名",
              label: {
                show: true,
                position: "right",
                fontSize: 14
              },
              barGap: "100%",
              barCategoryGap: "50%",
              data: data
            }
          ]
        };
        this.load1 = "load";
        this.option1 = opt;
      } catch (e) {
        // console.error(e);
        this.load1 = "error";
      }
    },
    async setOption2() {
      try {
        this.weeksPower = await getWeeksPower(this.comId, this.selectedWeek);
        const { weekBZClies: cur, weekSZClies: last } = this.weeksPower;
        if (
          cur instanceof Array &&
          cur.length > 0 &&
          (last instanceof Array && last.length > 0)
        ) {
          const curData = [],
            lastData = [];
          for (let i = 0; i < 7; i++) {
            curData.push(cur[i] || '-');
            lastData.push(last[i] || '-');
          }
          const opt = {
            color: colors,
            textStyle: {
              color: textColor
            },
            tooltip: {
              trigger: "axis",
              axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
              },
              formatter: function(p) {
                if (p.length < 2) {
                  return `${p[0].name}<br>
              ${p[0].seriesName}: ${p[0].value}<br>`;
                }
                const per = (
                  ((p[1].value - p[0].value) / p[0].value) *
                  100
                ).toFixed(2);
                const r = `${p[0].name}<br>
            ${p[0].seriesName}: ${p[0].value}<br>
            ${p[1] && p[1].seriesName}: ${p[1] && p[1].value}<br>
            ${p[1] && p[1].value < p[0].value ? "同比下降" : "同比增长"} : 
            ${Math.abs(per) || '-'}%`;
                return r;
              }
            },
            legend: {
              ...legend,
              data: ["上周电量", "本周电量"]
            },
            grid: {
              ...grid,
              top: "15%"
            },
            xAxis: [
              {
                type: "category",
                data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
                axisLine: {
                  lineStyle: {
                    color: textColor
                  }
                },
                axisTick: {
                  show: false
                }
              }
            ],
            yAxis: [
              {
                type: "value",
                name: "kw.h",
                splitLine: {
                  show: false
                },
                axisTick: {
                  show: false
                },
                axisLine: {
                  lineStyle: {
                    color: textColor
                  }
                }
              }
            ],
            series: [
              {
                name: "上周电量",
                type: "bar",
                // label: { show: true },
                data: lastData,
                barWidth: "8px",
                barGap: "50%"
              },
              {
                name: "本周电量",
                type: "bar",
                // label: { show: true },
                data: curData,
                barWidth: "8px"
              }
            ]
          };
          this.load2 = "load";
          this.option2 = opt;
        } else {
          this.load2 = "empty";
        }
      } catch (e) {
        this.load2 = "error";
      }
    },
    setOption3() {
      const data1 = [],
        data1_1 = [],
        yData1 = [];

      this.yearValue.forEach(e => {
        yData1.push(e.year);
        if (e.year === this.curYear) {
          data1.push({
            itemStyle: { color: activeColor },
            value: (parseInt(e.totalPower) / 10000).toFixed(2)
          });
          data1_1.push({
            itemStyle: { color: activeColor1 },
            value: (parseInt(e.monthpower) / 10000).toFixed(2)
          });
        } else {
          data1.push((parseInt(e.totalPower) / 10000).toFixed(2));
          data1_1.push((parseInt(e.monthpower) / 10000).toFixed(2));
        }
      });

      const option = {
        legend,
        textStyle: {
          color: textColor
        },
        tooltip: {},
        xAxis: [{ gridIndex: 0, name: "万kw.h", show: false }],
        yAxis: [
          {
            type: "category",
            gridIndex: 0,
            axisLine: { show: false },
            axisTick: { show: false },
            data: yData1
          }
        ],
        grid: {
          ...grid
        },
        series: [
          // These series are in the first grid.
          {
            type: "bar",
            name: "年总用电量",
            stack: "年用电情况",
            // label: { show: true, position: "inside", color: textColor },
            itemStyle: {
              color: color
            },
            barWidth: 20,
            data: data1
          },
          {
            type: "bar",
            name: "年购买量",
            stack: "年用电情况",
            itemStyle: {
              color: color1
            },
            label: {
              show: true,
              position: "inside",
              color: textColor
            },
            barWidth: 20,
            data: data1_1
          }
        ]
      };
      this.load3 = "load";
      this.option3 = option;
    },
    setOption4() {
      if (!this.curMonthPower) {
        this.load4 = "empty";
        return;
      }
      const preTotal = toWanKwH(this.curMonthPower.monthpower),
        useTotal = toWanKwH(this.curMonthPower.totalPower),
        warnPer = 0.9,
        color = colors[0],
        warnColor = colors[1];

      const option = {
        tooltip: {
          formatter: "已使用电量: {c}{b}"
        },
        xAxis: [],
        yAxis: [],
        grid: [],
        series: [
          // These series are in the first grid.
          {
            type: "gauge",
            center: ["50%", "60%"], // 默认全局居中
            splitNumber: 5, // 刻度数量
            min: 0,
            max: preTotal,
            startAngle: 210,
            endAngle: -30,
            clockwise: true,
            title: {
              textStyle: {
                color: color
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                width: 20,
                shadowBlur: 0,
                color: [[warnPer, color], [1, warnColor]]
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: color,
                width: 1
              }
            },
            splitLine: {
              show: false,
              length: -20,
              lineStyle: {
                color: color
              }
            },
            axisLabel: {
              show: true,
              distance: -4,
              textStyle: {
                color: color,
                fontSize: 10
              }
            },
            pointer: {
              // 仪表盘指针
              show: true,
              width: 4
            },
            detail: {
              show: true,
              textStyle: {
                fontSize: 16,
                textAlign: "center",
                lineHeight: 24
              },
              formatter: function(value) {
                return (
                  "已使用\n" +
                  value +
                  "(" +
                  ((value / preTotal) * 100).toFixed(2) +
                  "%)"
                );
              }
            },
            data: [
              {
                name: "万kw.h",
                value: useTotal
              }
            ]
          }
        ]
      };
      this.load4 = "load";
      this.option4 = option;
    },
    setOption5() {
      const xData = [];
      const data2 = [];
      const data2_1 = [];
      this.yearValue.forEach(e => {
        if (e.year === this.curYear) {
          for (let i = 1; i <= 12; i++) {
            xData.push(i);
            if (!e.cliesMonth) {
              data2.push(null);
              data2_1.push(null);
              continue;
            }
            const a = e.cliesMonth.find(b => b.month === i);
            if (a) {
              if (
                this.selectMonthes.indexOf(this.curYear + "-" + a.month) >= 0
              ) {
                data2.push({
                  itemStyle: { color: activeColor },
                  value: (parseInt(a.totalPower) / 10000).toFixed(2)
                });
                data2_1.push({
                  itemStyle: {
                    color: activeColor1
                  },
                  value: (parseInt(a.monthpower) / 10000).toFixed(2)
                });
              } else {
                data2.push((parseInt(a.totalPower) / 10000).toFixed(2));
                data2_1.push((parseInt(a.monthpower) / 10000).toFixed(2));
              }
            } else {
              data2.push(null);
              data2_1.push(null);
            }
          }
        }
      });

      const option = {
        legend,
        textStyle: {
          color: textColor
        },
        title: {
          text: this.curYear + "年用电量(kw.h/月)",
          ...title
        },
        tooltip,
        xAxis: [
          {
            type: "category",
            name: "月份",
            // axisLine: {
            //   lineStyle: {
            //     color: "#fff"
            //   }
            // },
            axisTick: { show: false },
            data: xData
          }
        ],
        yAxis: [
          {
            name: "万kw.h",
            type: "value",
            splitLine: {
              show: false
            },
            // axisLine: {
            //   lineStyle: {
            //     color: "#fff"
            //   }
            // },
            axisTick: {
              show: false
            }
          }
        ],
        grid: {
          ...grid,
          top: 60
        },
        series: [
          // // These series are in the second grid.
          {
            type: "bar",
            name: "月用电量",
            // stack: "月用电情况",
            barWidth: 16,
            label: { show: false, position: "inside" },
            itemStyle: {
              color: color
            },
            data: data2
          },
          {
            type: "bar",
            name: "月购买量",
            // stack: "月用电情况",
            barWidth: 16,
            label: { show: false, position: "top", color: "#666" },
            barGap: "40%",
            itemStyle: {
              color: color1
            },
            data: data2_1
          }
        ]
      };
      this.load5 = "load";
      this.option5 = option;
    },
    async setOption6() {
      const data3 = [],
        lData = [];
      let xData3 = [];
      forEach(this.dateValue, (d, k) => {
        const _data = [];
        if (d.select) {
          lData.push(k);
          const n = getMonthDay(k);
          for (let i = 1; i <= n; i++) {
            xData3.push(i);
            const a = d.data.filter(e => i === e.day)[0];
            if (a) {
              _data.push(Math.round(a.totalPower));
              // _data_1.push(a.monthpower);
            } else {
              _data.push(null);
              // _data_1.push(null);
            }
          }
        }
        _data.length &&
          data3.push({
            name: k,
            type: "line",
            data: _data
          });
      });
      // xData3 去重
      xData3 = uniq(xData3);
      const option = {
        legend,
        textStyle: {
          color: textColor
        },
        color: colors,
        tooltip: {
          trigger: "axis"
        },
        xAxis: {
          data: xData3,
          axisLine: { lineStyle: { color: textColor } },
          axisTick: { show: false }
        },
        yAxis: {
          type: "value",
          name: "kw.h",
          axisLine: { lineStyle: { color: textColor } },
          axisTick: { show: false },
          splitLine: { show: false }
        },
        grid,
        series: data3
      };
      // this.echarts6.setOption(option, true);
      this.option6 = option;
    },
    // async getWeeksPower() {
    //   const data = await getWeeksPower(this.comId, this.selectedWeek);
    //   this.weeksPower = data;
    // },
    echart3Click(p) {
      const { name } = p;
      this.curYear = parseInt(name);
      this.setOption3();
      this.setOption5();
    },
    echart5Click(p) {
      const { name } = p;
      this.curMonth = parseInt(name);
      const i = this.selectMonthes.indexOf(this.curYear + "-" + name);
      if (i >= 0) {
        this.selectMonthes.splice(i, 1);
      } else {
        this.selectMonthes.push(this.curYear + "-" + name);
      }
      this.setOption4();
      this.setOption5();
      this.getDatePower(this.curYear + "-" + name);
    },
    dateChange(v) {
      this.setOption2();
    },
    getYearMonth() {
      if (this.yearValue instanceof Array) {
        const a = this.yearValue[0];
        if (a instanceof Object) {
          this.curYear = a.year;
          if (a.cliesMonth instanceof Array) {
            const b = a.cliesMonth[0];
            if (b instanceof Object) {
              this.selectMonthes.push(a.year + "-" + b.month);
              this.curMonth = b.month;
            }
          }
        }
      }
    },
    async getDatePower(m) {
      if (!m) return;
      const [year, month] = m.split("-");
      if (!this.dateValue[m]) {
        this.$set(this.dateValue, m, {});
        const res = await getDayBuyElec(this.comId, year, month);
        this.$set(this.dateValue[m], "data", res.data);
        this.$set(this.dateValue[m], "select", true);
      } else {
        this.$set(this.dateValue[m], "select", !this.dateValue[m].select);
      }
      this.setOption6();
    }
  }
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  display: grid;
  grid-template-columns: 40% auto;
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 10px;
  grid-auto-flow: column;
}

.echarts2-wrapper {
  position: relative;
  .date-select {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9;
    .el-input {
      width: 130px;
    }
  }
  /deep/ .el-date-editor {
    margin-top: 4px;
    margin-left: 8px;
    border: 0;
    width: 110px !important;
    .el-input__prefix {
      display: none;
    }
    input {
      background: transparent;
      // color: #fff;
      padding: 0 10px;
      border: 0;
      // width: 80px;
    }
  }
}
.echarts3-wrapper {
  grid-row-start: 1;
  grid-row-end: 3;
  box-sizing: border-box;
  >>> .power-wrapper {
    display: flex;
    height: 100%;
    flex-direction: column;
  }
  .year-power {
    border-bottom: 1px solid #eee;
    min-height: 100px;
    height: 25%;
    display: flex;
    align-items: center;
    position: relative;
    & > div:nth-child(1) {
      border-right: 1px solid #eee;
      height: 100%;
      padding: 0 20px;
      display: flex;
      flex-shrink: 0;
      align-items: center;
      p {
        line-height: 1.6;
        margin: 0;
      }
    }
    .echarts {
      flex-grow: 1;
    }
  }
  .month-power {
    flex: 1;
    margin-top: 10px;
  }
}
.h {
  margin: 0px 0;
}
</style>
